package com.shuqi.activity.viewport;

import com.shuqi.common.utils.Log4an;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

/**
 * 侧滑目录
 * 
 * @author zp
 * 
 */
public class LeftSliderLayout extends ViewGroup {

    public final static int OPEN = 1;
    public final static int CLOSE = 2;
    private int status = CLOSE;

    public Scroller mScroller;
    private VelocityTracker mVelocityTracker;

    /**
     * Constant value for touch state TOUCH_STATE_REST : no touch TOUCH_STATE_SCROLLING : scrolling
     * TOUCH_STATE_CONTROL : 滑动目录
     */
    private static final int TOUCH_STATE_REST = 0;
    private static final int TOUCH_STATE_SCROLLING = 1;
    private static final int TOUCH_STATE_CONTROL = 2;
    private int mTouchState = TOUCH_STATE_REST;

    /**
     * 触发移动事件的最短距离，如果小于这个距离就不触发移动控件
     */
    private int mTouchSlop;

    /**
     * 标记xy坐标最后的触摸值
     */
    private float mLastMotionX;
    private float mLastMotionY;

    /**
     * 当前速度值计算和滑动距离 VELOCITY_UNITS in dp mVelocityUnits in px
     */
    private static final int VELOCITY_UNITS = 800;
    private int mVelocityUnits;

    /**
     * 最低速度确定方向 MINOR_VELOCITY in dp mMinorVelocity in px
     */
    private static final float MINOR_VELOCITY = 150.0f;
    private int mMinorVelocity;
    /**
     * 阴影尺寸 VELOCITY_UNITS in dp mVelocityUnits in px
     */
    private static final float DEF_SHADOW_WIDTH = 10.0f;
    private int mDefShadowWidth;

    private View mMainChild = null;
    private OnLeftSliderLayoutStateListener mListener = null;

    public LeftSliderLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LeftSliderLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mScroller = new Scroller(context);
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();

        /**
         * dp转换成px
         * 
         */
        final float fDensity = getResources().getDisplayMetrics().density;
        mVelocityUnits = (int) (VELOCITY_UNITS * fDensity + 0.5f);
        mMinorVelocity = (int) (MINOR_VELOCITY * fDensity + 0.5f);
        mDefShadowWidth = (int) (DEF_SHADOW_WIDTH * fDensity + 0.5f);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // check Measure Mode is Exactly.
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        if (widthMode != MeasureSpec.EXACTLY) {
            throw new IllegalStateException(
                    "LeftSliderLayout only canmCurScreen run at EXACTLY mode!");
        }
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode != MeasureSpec.EXACTLY) {
            throw new IllegalStateException("LeftSliderLayout only can run at EXACTLY mode!");
        }

        // measure child views
        int nCount = getChildCount();
        for (int i = 2; i < nCount; i++) {
            removeViewAt(i);
        }
        nCount = getChildCount();
        if (nCount > 0) {
            if (nCount > 1) {
                mMainChild = getChildAt(0);
                getChildAt(1).measure(widthMeasureSpec, heightMeasureSpec);
            } else {
                mMainChild = getChildAt(0);
            }
            mMainChild.measure(widthMeasureSpec, heightMeasureSpec);
        }

        // 初始化滑动位置
        if (status == CLOSE) {
            scrollTo(mVelocityUnits, 0);
        } else {
            scrollTo(mScroller.getCurrX(), 0);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int nCount = getChildCount();
        if (nCount <= 0) {
            return;
        }

        // 设置主view宽高
        if (mMainChild != null) {
            mMainChild.layout(l, t, l + mMainChild.getMeasuredWidth(),
                    t + mMainChild.getMeasuredHeight());
        }

        // 设置阴影宽高
        if (nCount > 1) {
            int nRightChildWidth = 0;
            View rightChild = getChildAt(1);
            ViewGroup.LayoutParams layoutParams = rightChild.getLayoutParams();
            if (layoutParams.width == ViewGroup.LayoutParams.FILL_PARENT
                    || layoutParams.width == ViewGroup.LayoutParams.FILL_PARENT) {
                nRightChildWidth = mDefShadowWidth;
            } else {
                nRightChildWidth = layoutParams.width;
            }
            rightChild.layout(l + mMainChild.getMeasuredWidth(), t,
                    l + mMainChild.getMeasuredWidth() + nRightChildWidth,
                    t + rightChild.getMeasuredHeight());
        }
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int nCurScrollX = getScrollX();
        // 检查触摸点是否在view上和是否在滑动过程中
        if (mMainChild != null && mTouchState != TOUCH_STATE_SCROLLING) {
            Rect rect = new Rect();
            mMainChild.getHitRect(rect);
            if (!rect.contains((int) event.getX() + nCurScrollX, (int) event.getY())) {
                if (nCurScrollX != mVelocityUnits) {
                    scrollByWithAnim(-nCurScrollX);
                }
                return false;
            }
        } else {
            return false;
        }

        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }

        mVelocityTracker.addMovement(event);

        final int action = event.getAction();
        final float x = event.getX();

        switch (action) {
            case MotionEvent.ACTION_DOWN: {
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                mLastMotionX = x;
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                // 通过滑动x坐标确定滑动事件
                int deltaX = (int) (mLastMotionX - x);
                if (nCurScrollX + deltaX < getMaxScrollX()) {
                    deltaX = getMaxScrollX() - nCurScrollX;
                    mLastMotionX = mLastMotionX - deltaX;
                } else if (nCurScrollX + deltaX > getMaxScrollX()) {
                    mLastMotionX = mLastMotionX - deltaX;
                } else {
                    mLastMotionX = x;
                }
                // 移动到正确定的位置
                if (deltaX != 0) {
                    scrollBy(deltaX, 0);
                }
                break;
            }

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP: {
                final VelocityTracker velocityTracker = mVelocityTracker;
                velocityTracker.computeCurrentVelocity(mVelocityUnits);
                // 设置是打开或者关闭动作
                if (nCurScrollX < 0) {
                    scrollByWithAnim(-nCurScrollX);
//                    setState(true);

                } else {
                    if (nCurScrollX > 0) {
                        int velocityX = (int) velocityTracker.getXVelocity();
                        if (velocityX > mMinorVelocity) {
                            scrollByWithAnim(-nCurScrollX);
//                            setState(true);
                        } else if (velocityX < -mMinorVelocity) {
                            scrollByWithAnim(-nCurScrollX + mVelocityUnits);
//                            setState(false);
                        } else if (nCurScrollX >= mMinorVelocity) {
                            scrollByWithAnim(-nCurScrollX + mVelocityUnits);
//                            setState(false);
                        } else {
                            scrollByWithAnim(-nCurScrollX);
//                            setState(true);
                        }

                    }

                }

                if (mVelocityTracker != null) {
                    mVelocityTracker.recycle();
                    mVelocityTracker = null;
                }

                mTouchState = TOUCH_STATE_REST;
                break;
            }

        }
        Log.e("mine", "mTouchState is show:" + mTouchState);
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        final int action = ev.getAction();

        if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
            return true;
        }

        final float x = ev.getX();
        final float y = ev.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mLastMotionX = x;
                mLastMotionY = y;
                mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
                break;

            case MotionEvent.ACTION_MOVE:
                final int xDiff = (int) Math.abs(mLastMotionX - x);
                if (xDiff > mTouchSlop) {
                    if (Math.abs(mLastMotionY - y) / Math.abs(mLastMotionX - x) < 1) {
                        mTouchState = TOUCH_STATE_CONTROL;
                    }
                }
                break;

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mTouchState = TOUCH_STATE_REST;
                break;
        }
//        if (mTouchState == 0) {
//            setState(false);
//        }
        return mTouchState != TOUCH_STATE_REST;
    }

    public boolean getLeftSliderState() {
        if (mScroller.isFinished()) {
            return true;
        }
        return false;
    }

    /**
     * 触摸动画移动
     * 
     * @param nDx x-axis offset
     */
    void scrollByWithAnim(int nDx) {
        if (nDx == 0) {
            return;
        }
        mScroller.startScroll(getScrollX(), 0, nDx, 0, Math.abs(nDx));
        if (nDx >= mVelocityUnits / 5) {
            status = CLOSE;
            setState(false);
            StatisticsUtils.onEvent(StatisticsEventID.BOOKCONTENT_CATALOG_SLIDE_BACK);
        }
        invalidate();
    }

    /**
     * 按钮打开或者关闭view
     * 
     * @param nDx x-axis offset
     */
    void oCCrollByWithAnim(int nDx) {
        if (nDx == 0) {
            return;
        }
        mScroller.startScroll(getScrollX(), 0, nDx, 0, Math.abs(VELOCITY_UNITS));
        invalidate();
    }

    /**
     * 设置滑动最大距离
     * 
     * @return distance in px
     */
    private int getMaxScrollX() {
        return 0;
    }

    /**
     * 关闭 LeftSlideLayout
     */
    public void close() {
        status = CLOSE;
        oCCrollByWithAnim(mVelocityUnits - getScrollX());
        setState(false);
    }

    /**
     * 打开 LeftSlideLayout
     */
    public void open() {
        status = OPEN;
        oCCrollByWithAnim((-1) * getScrollX());
        setState(true);
    }

    /**
     * 判断是否打开
     * 
     * @return
     */
    public boolean isOpen() {
        return status == OPEN ? true : false;
    }

    /**
     * Set state of LeftSliderLayout
     * 
     * @param bIsOpen the new state
     */
    private void setState(boolean bIsOpen) {
        int nCurScrollX = getScrollX();
        if (mListener != null) {
            mListener.OnLeftSliderLayoutStateChanged(bIsOpen);
        }
    }

    /**
     * Set listener to LeftSliderLayout
     */
    public void setOnLeftSliderLayoutListener(OnLeftSliderLayoutStateListener listener) {
        mListener = listener;
    }

    /**
     * LeftSliderLayout Listener
     * 
     */
    public interface OnLeftSliderLayoutStateListener {

        /**
         * Called when LeftSliderLayout’s state has been changed.
         * 
         * @param bIsOpen the new state
         */
        public void OnLeftSliderLayoutStateChanged(boolean bIsOpen);

    }
}
